package com.sh.utils;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/websocket")
@Component
@Slf4j
public class WebSocket {


    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 建立连接成功
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        session.getAsyncRemote().sendText("连接成功");
        session.getUserProperties().put("sessionId", session.getId());
        this.session = session;
        webSocketSet.add(this);
        log.info("【websocket 消息】有新的连接，总数{}", webSocketSet.size());
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        this.session = session;
        webSocketSet.remove(this);
        log.info("【websocket消息】 连接断开，总数{}", webSocketSet.size());
    }

    /**
     * 接收客户端消息
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("消息" + message);
        log.info("【websocket消息】 收到客户端发来的消息：{}", message);
    }

    /**
     * 发送消息给所有客户端
     */
    public void sendMessageToAllClients(String obj) {
        for (WebSocket webSocket : webSocketSet) {
            try {
                if (webSocket.session != null && webSocket.session.isOpen()) {
                    webSocket.session.getBasicRemote().sendText(obj);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}